﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CustomsSystem.BLL;
using CustomsSystem.Common;
using System.IO;
using System.Security.AccessControl;
using Maticsoft.Common;
using CustomsSystem.Model;
namespace WEB.Form
{
    public partial class FormEdit : baseFile
    {
        public DataTable dt;
        CustomsSystem.Model.info_formMaster fmModel = new CustomsSystem.Model.info_formMaster();
        CustomsSystem.Model.info_form fModel = new CustomsSystem.Model.info_form();
        int id;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["ID"] != null)//修改页面
                {
                    id = Convert.ToInt32(Request.QueryString["ID"]);
                    fmModel = fmBll.GetModel(id);
                    tb_Name.Text = fmModel.formName;//载入模板名
                    tb_Name.Enabled = false;
                    gv_Form.DataSource = fBll.GetList("Fid=" + fmModel.ID).Tables[0];//获取详细的数据
                    gv_Form.DataBind();
                    bt_save.Text = "修改";

                }
                else
                {
                    Bind();
                }
            }
        }
        /// <summary>
        /// 添加一行数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bt_NewRow_Click(object sender, EventArgs e)
        {
                gv_Form.DataSource = getData();
                gv_Form.DataBind();
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bt_save_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] != null)//修改页面
            {
                 id = Convert.ToInt32(Request.QueryString["ID"]);
            }
            if (id<=0)//可以修改说明不是修改页面
            {
                if (checkModelName())//模板名存在
                {
                    return;
                }
            }
            string cell = (gv_Form.Rows[0].Cells[0].FindControl("tb_SQL") as TextBox).Text;//第二个文本框判断数据是否为空
            if (cell.Trim() == "")
            {
                MessageBox.Show(this, "请填入数据！");
                return;
            }
            string colIndex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//为了转换成数值
            foreach (GridViewRow dr in gv_Form.Rows)//判断格式
            {
                string cell1 = (dr.Cells[0].FindControl("tb_cell") as TextBox).Text;
                string cell2 = (dr.Cells[1].FindControl("tb_SQL") as TextBox).Text;
                if (cell1 != "" && cell2 != "")
                {
                    if (colIndex.IndexOf(cell1.Substring(0, 1).ToUpper()) < 0)
                    {
                        MessageBox.Show(this, "请注意格式");
                        return;
                    }
                    if (cell2.ToLower().IndexOf("s") < 0 || cell2.ToLower().IndexOf("f") < 0 || cell2.ToLower().IndexOf("w") < 0)
                    {
                        MessageBox.Show(this, "请注意格式");
                        return;
                    }
                }
            }
            //上传文件的名
            string fileName = DateTime.Now.ToShortDateString() + tb_Name.Text + ".xls";
            string msg = UpExcel(fileName);

            if (msg != "OK")//上传文件错误
            {
                MessageBox.Show(this, msg);
                return;
            }
            int fid = 0;
            fmModel.formName = tb_Name.Text;
            fmModel.ExcelPath = fileName;
            if (id<=0)//增加
            {
                fid = fmBll.Add(fmModel);
            }
            else//修改
            {
                fmModel.ID = id;
                fmBll.Update(fmModel);
                fid = fmModel.ID;
            }
            if (fid > 0)//保存info_form表的数据
            {
                foreach (GridViewRow dr in gv_Form.Rows)
                {
                    fModel.FID = fid;
                    fModel.cell = (dr.Cells[0].FindControl("tb_cell") as TextBox).Text;
                    if (fModel.cell.ToString() == "")//两个空格都不可以没数据
                    {
                        continue;
                    }
                    fModel.toSQL = (dr.Cells[1].FindControl("tb_SQL") as TextBox).Text;
                    if(fModel.toSQL.ToString()=="")//没数据不保存
                    {
                        continue;
                    }
                    string keyid = gv_Form.DataKeys[dr.RowIndex].Value.ToString();
                    if (keyid == "")//新加行没有Datakey
                    {
                        fBll.Add(fModel);
                    }
                    else
                    {
                        fModel.ID = Convert.ToInt32(keyid);
                        fBll.Update(fModel);
                    }
                }
                MessageBox.ShowAndRedirect(this, "操作成功！", "./FormView.aspx");
            }
            else
            {
                MessageBox.Show(this, "操作失败！");
            }
        }
        ///// <summary>
        ///// 导出excel测试按钮
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void Button1_Click(object sender, EventArgs e)
        //{
        //    int id = 1;//模板的id
        //    string name = fmBll.GetModel(id).ExcelPath;//excel的名字
        //    string path = Server.MapPath("~/document/ExcelForm/" + name);//模板Excel的地址
        //    string ExcelName = "00.xls";//新的Excel名
        //    string newpath = Server.MapPath("~/document/ExcelForm/" + ExcelName);//新的Excel的名字
        //    CopyDir(path, newpath);//复制Excel
        //    string sheetID="1,1,1,1,1,1,1,1";//单号
        //    string date = "between '2013.1.06' and '2013.12.30'";//日期
        //     fBll.Exesql(id,sheetID,newpath,date);//获取sql的值
        //    DownloadFile(newpath);//下载文件

        //}
        /// <summary>
        /// 模板名字的检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tb_Name_TextChanged(object sender, EventArgs e)
        {
            checkModelName();//检查模板名
        }
        #region 数据处理
        /// <summary>
        /// 绑定空表
        /// </summary>
        void Bind()
        {
            dt = new DataTable("table");
            //新建两行
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("cell", typeof(string));
            dt.Columns.Add("toSQL", typeof(string));

            for (int i = 0; i < 10; i++)
            {
                DataRow newrow = dt.NewRow();
                dt.Rows.Add(newrow);
                dt.AcceptChanges();
            }
            //绑定空行
            gv_Form.DataSource = dt;
            gv_Form.DataBind();

        }
        /// <summary>
        /// 获取gv的数据
        /// </summary>
        /// <returns></returns>
        public DataTable getData()
        {
            dt = new DataTable("table");
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("cell", typeof(string));
            dt.Columns.Add("toSQL", typeof(string));
            //去gv的数据
            foreach (GridViewRow dr in gv_Form.Rows)
            {
                DataRow newrow = dt.NewRow();
                newrow[0] = gv_Form.DataKeys[dr.RowIndex].Value.ToString();
                newrow[1] = (dr.FindControl("tb_cell") as TextBox).Text;
                newrow[2] = (dr.FindControl("tb_SQL") as TextBox).Text;
                dt.Rows.Add(newrow);
                dt.AcceptChanges();
            }
            //添加空行
            DataRow row = dt.NewRow();
            dt.Rows.Add(row);
            dt.AcceptChanges();
            return dt;//返回数据表
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileName"></param>
        public string UpExcel(string fileName)
        {
            //上传文件
            if (Fup_Excel.HasFile)//是否有文件
            {
                #region 文件上传
                string FileExc = System.IO.Path.GetExtension(Fup_Excel.FileName);//获取文件后缀
                string msg = "";
                if (FileExc != ".xls")//判断是否为Excel文件
                {
                    msg = "只能为xls文件！";
                }
                if (Fup_Excel.PostedFile.ContentLength > 10 * 1024 * 1024)
                {
                    msg += "文件大小不能超过10M";
                }
                if (msg != "")
                {
                    return msg;
                }
                else
                {
                    string path = Server.MapPath("~/document/ExcelForm/" + fileName);//上传文件
                    if (System.IO.File.Exists(path))//存在文件就删除文件
                    {
                        System.IO.File.Delete(path);
                    }
                    Fup_Excel.SaveAs(path);//保存文件
                    return "OK";
                }
                #endregion
            }
            else
            {
                if (!tb_Name.Enabled)
                {
                    fileName = null;//没有上传文件不需要录入(修改的时候)
                    return "OK";
                }
                else
                {
                    return "请选择上传的Excel！";
                }
            }
        }
        /// <summary>
        /// 检查模板名是否存在
        /// </summary>
        /// <returns></returns>
        public bool checkModelName()
        {
            if (tb_Name.Text.Trim() == "")
            {
                lb_msg.Text = "模板名不能为空";
                lb_msg.ForeColor = System.Drawing.Color.Red;
                lb_msg.Visible = true;
                return true;
            }
            //判断模板名字知否存在
            else if (fmBll.GetList("formName= '" + tb_Name.Text + "'").Tables[0].Rows.Count > 0)
            {
                lb_msg.Text = "该模板名已经存在，请重新输入！";
                lb_msg.ForeColor = System.Drawing.Color.Red;
                lb_msg.Visible = true;
                return true;
            }
            else
            {
                lb_msg.Text = "该模板名可以使用！";
                lb_msg.ForeColor = System.Drawing.Color.Green;
                lb_msg.Visible = true;
                return false;
            }
        }
        #endregion

      

    }

}
